package com.taptech.doufu.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.taptech.doufu.ui.activity.base.DiaobaoBaseActivity;
import com.taptech.doufu.util.TTLog;
import com.taptech.doufu.R;
import com.taptech.doufu.bean.CommentDataBean;
import com.taptech.doufu.ui.adapter.NovelReplyAdapter;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.listener.HttpResponseListener;
import com.taptech.doufu.services.personalcenter.AccountService;
import com.taptech.doufu.services.PersonalNoteService;
import com.taptech.doufu.util.at.AtClickListen;
import com.taptech.doufu.util.at.AtUtil;
import com.taptech.doufu.util.DiaobaoUtil;
import com.taptech.doufu.util.TMAnalysis;
import com.taptech.doufu.util.UIUtil;
import com.taptech.doufu.net.httputils.HttpResponseObject;
import com.taptech.doufu.ui.view.PullToRefreshListView;
import com.taptech.doufu.ui.view.WaitDialog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by lsy on 2015/9/15.
 */
public class NewPersonalNoteDesActivity extends DiaobaoBaseActivity implements View.OnClickListener, HttpResponseListener
{

    private String id;
    private String object_type = PersonalNoteService.OBJECT_TYPE_NOTE;
    //加载等待窗
    WaitDialog mWaitDialog;
    //评论列表
    private PullToRefreshListView mCommentListView;
    private NovelReplyAdapter adapter;
    private String last = "";
    private boolean hasMoreComment = true;
    private ImageView hasNoMoreCommentImg;
    //发表评论
    private EditText mCommentEditView;
    private Button mSendCommentBtn;
    private TextView tv_at;
    private View comment_view;

    View mHeaderView;
    PersonalNoteDesActivity mHeaderViewHandle;
    View flagGroup;
    private boolean isLoadingComplete = true;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal_note_dse_layout);
        initData();
        initHeaderView();
        initView();
        if (isLoadingComplete)
        {
            isLoadingComplete = false;
            PersonalNoteService.getInstance().loadCommentList(NewPersonalNoteDesActivity.this, id, object_type, "");
        }

    }

    private void initData()
    {
        Intent intent = getIntent();
        id = intent.getStringExtra(Constant.ARTICLE_ID);
        object_type = intent.getStringExtra(Constant.OBJECT_TYPE);
        // 友盟统计

        if (object_type.equals("41"))
        {
            TMAnalysis.event(this, "note-detail-info");
        } else if (object_type.equals("42"))
        {
            TMAnalysis.event(this, "draw-detail-info");
        } else if (object_type.equals("43"))
        {
            TMAnalysis.event(this, "coser-detail-info");
        }
    }


    private void initHeaderView()
    {
        mHeaderView = LayoutInflater.from(this).inflate(R.layout.activity_personal_note_des_head_layout, null);
        mHeaderViewHandle = new PersonalNoteDesActivity();
        mHeaderViewHandle.init(this, mHeaderView, id, object_type);
        mHeaderViewHandle.setHandler(mhandler);
    }

    Handler mhandler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            switch (msg.what)
            {
                case 0:
                    comment_view.setVisibility(View.GONE);
                    break;
                case 1:
                    comment_view.setVisibility(View.VISIBLE);
                    break;
            }
            super.handleMessage(msg);
        }
    };
    int position;
    int touchSlop = 10;

    private void initView() {
        touchSlop = (int) (ViewConfiguration.get(NewPersonalNoteDesActivity.this).getScaledTouchSlop() * 0.9);//滚动过多少距离后才开始计算是否隐藏/显示头尾元素。这里用了默认touchslop的0.9倍。
        hasNoMoreCommentImg = (ImageView) findViewById(R.id.no_more_comment_img);
        hasNoMoreCommentImg.setVisibility(View.GONE);
        mCommentListView = (PullToRefreshListView) findViewById(R.id.draw_comment_listview);
        mCommentListView.setLoadmoreable(true);
        mCommentListView.addHeaderView(mHeaderView);
        //  setlis();
        mCommentListView.setOnTouchListener(onTouchListener);
        mCommentListView.setOnScrollListener(onScrollListener);
        mCommentListView.setOnScrollToBottomListener(new PullToRefreshListView.OnScrollToBottomListener()
        {
            @Override
            public void OnScrollToBottom()
            {
                loadComment();
            }
        });
        adapter = new NovelReplyAdapter(this);
        mCommentListView.setAdapter(adapter);
        //发表评论
        mCommentEditView = (EditText) findViewById(R.id.contents_acticity_comment_text);
        mSendCommentBtn = (Button) findViewById(R.id.contents_acticity_send_btn);
        mSendCommentBtn.setVisibility(View.VISIBLE);
        flagGroup = findViewById(R.id.contents_acticity_flag_group);
        flagGroup.setVisibility(View.GONE);
        //初始化@控件
        comment_view = findViewById(R.id.novel_flower_acticity_publish_comment);
        comment_view.setVisibility(View.VISIBLE);
        initAt();
        initWaitWindow();
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus)
    {
        super.onWindowFocusChanged(hasFocus);
        mHeaderViewHandle.setTagMoreBtnVisible();
    }

    View.OnTouchListener onTouchListener = new View.OnTouchListener()
    {


        float lastY = 0f;
        float currentY = 0f;
        //下面两个表示滑动的方向，大于0表示向下滑动，小于0表示向上滑动，等于0表示未滑动
        int lastDirection = 0;
        int currentDirection = 0;

        @Override
        public boolean onTouch(View v, MotionEvent event)
        {
            switch (event.getAction())
            {
                case MotionEvent.ACTION_DOWN:
                    lastY = event.getY();
                    currentY = event.getY();
                    currentDirection = 0;
                    lastDirection = 0;
                    break;
                case MotionEvent.ACTION_MOVE:
                    if (mCommentListView.getFirstVisiblePosition() > 0)
                    {
                        //只有在listView.getFirstVisiblePosition()>0的时候才判断是否进行显隐动画。因为listView.getFirstVisiblePosition()==0时，
                        //ToolBar——也就是头部元素必须是可见的，如果这时候隐藏了起来，那么占位置用了headerview就被用户发现了
                        //但是当用户将列表向下拉露出列表的headerview的时候，应该要让头尾元素再次出现才对——这个判断写在了后面onScrollListener里面……
                        float tmpCurrentY = event.getY();
                        if (Math.abs(tmpCurrentY - lastY) > touchSlop)
                        {//滑动距离大于touchslop时才进行判断
                            currentY = tmpCurrentY;
                            currentDirection = (int) (currentY - lastY);
                            if (lastDirection != currentDirection)
                            {
                                //如果与上次方向不同，则执行显/隐动画
                                if (currentDirection < 0)
                                {
                                    //animateHide();
                                    TTLog.i("TAG", "isupisup");
                                    comment_view.setVisibility(View.GONE);


                                } else
                                {
                                    //animateBack();
                                    comment_view.setVisibility(View.VISIBLE);
                                    TTLog.i("TAG", "isDownisDown");
                                }
                            }
                            lastY = currentY;
                        }
                    }
                    break;
                case MotionEvent.ACTION_CANCEL:
                case MotionEvent.ACTION_UP:
                    //手指抬起的时候要把currentDirection设置为0，这样下次不管向哪拉，都与当前的不同（其实在ACTION_DOWN里写了之后这里就用不着了……）
                    currentDirection = 0;
                    lastDirection = 0;
                    break;
            }
            return false;
        }
    };


    AbsListView.OnScrollListener onScrollListener = new AbsListView.OnScrollListener()
    {

        //这个Listener其实是用来对付当用户的手离开列表后列表仍然在滑动的情况，也就是SCROLL_STATE_FLING
        int state = SCROLL_STATE_IDLE;

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState)
        {
            //记录当前列表状态
            state = scrollState;
            switch (scrollState)
            {
                // 当不滚动时
                case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:// 是当屏幕停止滚动时
                    // 判断滚动到底部
                    if (mCommentListView.getLastVisiblePosition() == (mCommentListView.getCount() - 1))
                    {
                        //toTopBtn.setVisibility(View.VISIBLE);

                        TTLog.i("TAG", "滑到底部");
                        comment_view.setVisibility(View.VISIBLE);
                        loadComment();
                    }
                    // 判断滚动到顶部
                    if (mCommentListView.getFirstVisiblePosition() == 0)
                    {
                        TTLog.i("TAG", "滑到顶部");
                        comment_view.setVisibility(View.VISIBLE);
                        //toTopBtn.setVisibility(View.GONE);
                    }

                    break;
            }
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount)
        {
        }
    };


    private void initAt()
    {
        // TODO Auto-generated method stub
        tv_at = (TextView) findViewById(R.id.contents_acticity_at);
        AtClickListen atClickListen = new AtClickListen(this, mCommentEditView, tv_at);
    }


    @Override

    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Constant.AT_RESULI)
        {
            if (data != null)
            {
                String textString = "";
                String user_id = data.getStringExtra("user_id");
                String user_nikename = data.getStringExtra("user_nikename");
                if (user_nikename != null)
                {
                    if (requestCode == Constant.AT_CLICK)
                    {
                        textString = mCommentEditView.getText().toString() + "@" + user_nikename + " ";
                    } else if (requestCode == Constant.AT_WRITE)
                    {
                        textString = mCommentEditView.getText().toString() + user_nikename + " ";
                    }
                    new AtUtil(mCommentEditView, textString, Constant.AT_WRITE);
                }
            }
        }
    }

    // 处理评论网络回应

    private void handleComment(HttpResponseObject response)
    {
        if (response.getStatus() == Constant.STATUS_SUCCESS)
        {
            CommentDataBean data = new CommentDataBean();
            try
            {
                data.setJson(((JSONObject) response.getData()).getJSONObject(Constant.COMMENT));
            } catch (JSONException e)
            {
                e.printStackTrace();
            }
            data.getUser().setName(AccountService.getInstance().getBaseAccount().getNickname());
            data.getUser().setIcon(AccountService.getInstance().getBaseAccount().getUser_head_img());
            // adapter.addRefreshData(data);
            List<Object> commentList = new ArrayList<Object>();
            commentList.add(data);
            adapter.addRefreshDatas(commentList);
            clearComment();
            //changeTip();
            // UIUtil.toastMessage(NovelDesToCommActivity.this,
            // "回复成“攻”");

        } else
        {
            UIUtil.toastMessage(NewPersonalNoteDesActivity.this, DiaobaoUtil.getErrorTips(response));
        }
    }


    private synchronized void loadComment()
    {
        if (hasMoreComment)
        {
            isLoadingComplete = false;
            PersonalNoteService.getInstance().loadCommentList(NewPersonalNoteDesActivity.this, id, object_type, last);
            hasMoreComment = false;
        }
    }

    /**
     * 发表评论模块
     */

    public void publishComment(View view)
    {
        if (!AccountService.getInstance().isLogin())
        {
            AccountService.getInstance().jumpToLogin();
            return;
        }
        if (object_type.equals("41"))
        {
            TMAnalysis.event(this, "note-send-comment");
        } else if (object_type.equals("42"))
        {
            TMAnalysis.event(this, "draw-send-comment");
        } else if (object_type.equals("43"))
        {
            TMAnalysis.event(this, "coser-send-comment");
        }
        mSendCommentBtn.setClickable(false);
        if (mCommentEditView.getText() != null && DiaobaoUtil.getStringSizeNoSpace(mCommentEditView.getText().toString()) > 0)
        {
            mWaitDialog.show();
            PersonalNoteService.getInstance().sendCommentToNote(this, id, object_type, mCommentEditView.getText().toString());
        } else
        {
            UIUtil.toastMessage(NewPersonalNoteDesActivity.this, "评论不能为空哦");
        }
    }

    private void clearComment()
    {
        mCommentEditView.setHint("我也说一句...");
        mCommentEditView.setText("");
        ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(mCommentEditView.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }

    private void initWaitWindow()
    {
        mWaitDialog = new WaitDialog(this, R.style.loadNovelDialog, "");
        mWaitDialog.setCanceledOnTouchOutside(false);
    }

    @Override
    public void handleResponse(int handleType, HttpResponseObject response)
    {
        if (response == null)
        {
            UIUtil.toastMessage(this, Constant.loadingFail);
            return;
        }

        if (response.getStatus() == Constant.STATUS_SUCCESS)
        {
            if (mWaitDialog != null && mWaitDialog.isShowing())
            {
                mWaitDialog.dismiss();
            }
            switch (handleType)
            {

                case PersonalNoteService.HANDLE_TYPE_LOAD_COMMENT_LIST:
                    isLoadingComplete = true;
                    mSendCommentBtn.setClickable(true);
                    JSONObject obj = (JSONObject) response.getData();
                    JSONArray array = null;
                    try
                    {
                        array = obj.getJSONArray("list");
                        if (array != null && array.length() > 0)
                        {
                            adapter.setSuperDatas(DiaobaoUtil.jsonArray2BeanList(CommentDataBean.class, array));
                        }
                        if (last.equals(obj.getString("last")) || array == null || array.length() == 0)
                        {
                            hasMoreComment = false;
                            hasNoMoreCommentImg.setVisibility(View.VISIBLE);
                            mCommentListView.setFull(true);
                            mCommentListView.loadMoreComplete();
                        } else
                        {
                            hasMoreComment = true;
                        }
                        if (obj.has("last"))
                        {
                            last = obj.getString("last");
                        }
                    } catch (JSONException e)
                    {
                        e.printStackTrace();
                    }
                    break;
                case PersonalNoteService.HANDLE_TYPE_SEND_COMENT:
                    // ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(mCommentEditView.getWindowToken(),0);
                    UIUtil.toastMessage(NewPersonalNoteDesActivity.this, "评论成功！");
                    mSendCommentBtn.setClickable(true);
                    handleComment(response);
                    break;
            }

        } else
        {
            if (response.getUser_msg() != null)
            {
                UIUtil.toastMessage(this, response.getUser_msg());
            } else
            {
                UIUtil.toastMessage(this, Constant.loadingFail);
            }
        }

    }


    @Override
    public void onClick(View view)
    {

    }


}
